package TCPDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress( 8888));
            System.out.println("Server started on port 8888...");
            while (true) {
                new Thread(new ServerTask(serverSocket.accept())).start();
            }
        } catch (IOException e) {
            System.out.println(e.getCause());
        }
    }

    static class ServerTask implements Runnable{
        private Socket mSocket;
        public ServerTask(Socket socket) {
            mSocket = socket;
        }

        @Override
        public void run() {
            try {
                ObjectInputStream inputStream = new ObjectInputStream(mSocket.getInputStream());
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(mSocket.getOutputStream());
                String message = inputStream.readUTF();
                System.out.println("客户端："+message);
                objectOutputStream.writeUTF("Hello,"+message+"\n");
                objectOutputStream.flush();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }finally {
                try {
                    mSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
